package com.aaa.interceptor;

import com.aaa.util.EmployeeContext;
import com.aaa.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
//    在Controller方法运行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            log.warn("未登录，不允许访问");
            response.setStatus(401);
            return false;
        }

        //如果令牌非法：拦截不放行，设置响应状态码401
        try {
//            JwtUtils.parseJWT(token);
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = claims.get("id", Integer.class);
            EmployeeContext.setEmployeeId(id);
        } catch (Exception e) {
            log.warn("令牌非法，不允许访问");
            response.setStatus(401);
            e.printStackTrace();
            return false;
        }

        //放行
        return true;
    }

//在Controller方法之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

//在Http响应之前执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      EmployeeContext.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
